package com.eascs.p2p.wallet.server.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.p2p.admin.service.impl.InvestObjectServiceImpl;
import com.eascs.p2p.common.entity.InvestObjectEntity;
import com.eascs.p2p.common.entity.InvestorEntity;
import com.eascs.p2p.common.entity.InvestorRecordEntity;
import com.eascs.p2p.common.entity.InvestorWalletEntity;
import com.eascs.p2p.common.entity.InvestorWalletFlowEntity;
import com.eascs.p2p.common.entity.InvestorWalletPayEntity;
import com.eascs.p2p.common.entity.InvestorWithdrawRecordEntity;
import com.eascs.p2p.common.vo.InvestorWithdrawRecordVO;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.p2p.common.vo.RepaymentVO;
import com.eascs.p2p.common.wallet.common.TransType;
import com.eascs.p2p.investor.server.InvestorServiceInner;
import com.eascs.p2p.wallet.dao.InvestorWalletDao;
import com.eascs.p2p.wallet.server.InvestorWalletServiceInner;

@Service
public class InvestorWalletServiceInnerImpl implements InvestorWalletServiceInner {
	private static Logger logger = LoggerFactory.getLogger(InvestorWalletServiceInnerImpl.class);

	@Autowired
	private InvestorWalletDao investorWalletDao;
	@Autowired
	private InvestorServiceInner investorService;
	@Autowired
	private InvestObjectServiceImpl investObjectService;

	@Override
	public ModelResult<InvestorWalletEntity> queryInvestorWallet(String investorId) {
		ModelResult<InvestorWalletEntity> result = new ModelResult<>();
		try {
			if (investorId.isEmpty()) {
				logger.error("获取钱包信息失败，参数为空, investorId:{}", investorId);
				return result.withError("InvestorWalletServiceInnerImpl.queryInvestorWallet", "获取钱包信息失败，参数为空");
			}
			InvestorWalletEntity vo = investorWalletDao.queryInvestorWallet(investorId);
			result.withModel(vo);
		} catch (Exception e) {
			logger.error("获取钱包信息失败, error:{}", e.getMessage());
			result.withError("InvestorWalletServiceInnerImpl.queryInvestorWallet", "获取钱包信息失败");
			e.printStackTrace();
			return result;
		}
		return result;
	}

	@Override
	public ModelResult<PageResult<InvestorWalletFlowEntity>> queryInvestorWalletFlowByPage(String investorId,
			int transType, int pageSize, int pageIndex) {
		ModelResult<PageResult<InvestorWalletFlowEntity>> result = new ModelResult<>();
		try {
			if (investorId.isEmpty()) {
				logger.error("获取钱包流水信息失败，参数为空, investorId:{}", investorId);
				return result.withError("InvestorWalletServiceInnerImpl.queryInvestorWallet", "获取钱包流水信息失败，参数为空");
			}
			PageResult<InvestorWalletFlowEntity> pageReult = investorWalletDao.findInvestorWalletFlowByPage(investorId,
					transType, pageSize, pageIndex);
			result.withModel(pageReult);
		} catch (Exception e) {
			logger.error("获取钱包流水信息失败, error:{}", e.getMessage());
			result.withError("InvestorWalletServiceInnerImpl.queryInvestorWalletFlowByPage", "获取钱包流水信息失败");
			e.printStackTrace();
			return result;
		}
		return result;
	}

	@Override
	@Transactional(transactionManager = "transactionManager")
	public ModelResult<Boolean> stopInvestWalletFlow(String investObjId) {
		ModelResult<Boolean> result = new ModelResult<>();
		if (investObjId == null || investObjId.isEmpty()) {
			logger.error("标的终止钱包流水报错，参数为空, investObjId:{}", investObjId);
			return result.withError("InvestorServiceInnerImpl.stopInvestWalletFlow", "标的终止钱包流水报错，参数为空");
		}
		ModelResult<InvestObjectEntity> investObjModelResult = investObjectService.findInvestObjectDetail(investObjId);
		if (!investObjModelResult.isSuccess() || investObjModelResult.getModel() == null) {
			logger.error("标的终止钱包流水报错，无法获取标的信息, investObjId:{}", investObjId);
			return result.withError("InvestorServiceInnerImpl.stopInvestWalletFlow", "标的终止钱包流水报错，无法获取标的信息");
		}
		InvestObjectEntity investObject = investObjModelResult.getModel();
		if (investObject.getObjectStatus() != InvestObjectEntity.OBJ_STATUS_PUBLISH) {
			logger.error("标的终止钱包流水报错，标的状态必须为发布中的，investObjId:{},investObjName:{}", investObjId,
					investObject.getTitle());
			return result.withError("InvestorServiceInnerImpl.stopInvestWalletFlow", "标的终止钱包流水报错，标的状态必须为投标中");
		}
		InvestorRecordEntity investorRecord = new InvestorRecordEntity();
		investorRecord.setObjectId(investObjId);
		investorRecord.setStatus(InvestorRecordEntity.STATUS_YES);
		ModelResult<List<InvestorRecordEntity>> modelResult = investorService.queryInvestorRecordList(investorRecord);
		if (modelResult.isSuccess()) {
			List<InvestorRecordEntity> recordList = modelResult.getModel();
			for (InvestorRecordEntity rec : recordList) {
				String investorId = rec.getInvestorId();
				BigDecimal investAmount = rec.getInvestAmount();
				InvestorWalletEntity investorWallet = investorWalletDao.queryInvestorWallet(investorId);
				if (investorWallet == null) {
					logger.error("标的终止钱包流水报错,钱包获取失败 ，investorId：" + investorId);
					throw new RuntimeException("标的终止钱包流水报错,钱包获取失败");
				}
				BigDecimal investFrozen = investorWallet.getInvestFrozen().subtract(investAmount);
				BigDecimal accumulateVote = investorWallet.getAccumulateVote().subtract(investAmount);
				BigDecimal currentBalance = investorWallet.getCurrentBalance().add(investAmount);
				investorWallet.setInvestFrozen(investFrozen);
				investorWallet.setAccumulateVote(accumulateVote);
				investorWallet.setCurrentBalance(currentBalance);
				int updateCount = investorWalletDao.updateInvestorWallet(investorWallet);
				if (updateCount <= 0) {
					logger.error("标的终止钱包流水报错,钱包更新失败,wallet:" + investorWallet.toString());
					throw new RuntimeException("标的终止钱包流水报错,钱包更新失败");
				}
				InvestorWalletFlowEntity investorWalletFlow = new InvestorWalletFlowEntity();
				try {
					BeanUtils.copyProperties(investorWalletFlow, investorWallet);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				investorWalletFlow.setTransType(TransType.FREEZE_TO_BALANCE);// 支付冻结转余额
				investorWalletFlow.setId(null);
				investorWalletFlow.setTransBalance(investAmount);
				int walletFlowCount = investorWalletDao.insertInvestorWalletFlow(investorWalletFlow);
				if (walletFlowCount <= 0) {
					logger.error("标的终止钱包流水报错,钱包流水添加失败,WalletFlow:" + investorWalletFlow.toString());
					throw new RuntimeException("标的终止钱包流水报错,钱包流水添加失败");
				}
				rec.setStatus(InvestorRecordEntity.STATUS_NO);
				ModelResult<Boolean> recodeResult = investorService.updateInvestorRecord(rec);
				if (!recodeResult.isSuccess() || !recodeResult.getModel()) {
					logger.error("标的终止钱包流水报错,修改投资记录状态报错,WalletFlow:" + rec.toString());
					throw new RuntimeException("标的终止钱包流水报错,修改投资记录状态报错");
				}
			}
		}
		result.setModel(true);
		return result;
	}

	@Override
	public ModelResult<Boolean> makeLoansInvestWalletFlow(String investObjId) {
		ModelResult<Boolean> result = new ModelResult<>();
		if (investObjId == null || investObjId.isEmpty()) {
			logger.error("标的放款钱包流水报错，参数为空, investObjId:{}", investObjId);
			return result.withError("InvestorServiceInnerImpl.makeLoansInvestWalletFlow", "标的放款钱包流水报错，参数为空");
		}
		ModelResult<InvestObjectEntity> investObjModelResult = investObjectService.findInvestObjectDetail(investObjId);
		if (!investObjModelResult.isSuccess() || investObjModelResult.getModel() == null) {
			logger.error("标的放款钱包流水报错，无法获取标的信息, investObjId:{}", investObjId);
			return result.withError("InvestorServiceInnerImpl.stopInvestWalletFlow", "标的放款钱包流水报错，无法获取标的信息");
		}
		InvestObjectEntity investObject = investObjModelResult.getModel();
		if (investObject.getObjectStatus() != InvestObjectEntity.OBJ_STATUS_FULL) {
			logger.error("标的放款钱包流水报错，标的状态必须为满标，investObjId:{},investObjName:{}", investObjId, investObject.getTitle());
			return result.withError("InvestorServiceInnerImpl.stopInvestWalletFlow", "标的放款钱包流水报错，标的状态必须为满标");
		}
		InvestorRecordEntity investorRecord = new InvestorRecordEntity();
		investorRecord.setObjectId(investObjId);
		investorRecord.setStatus(InvestorRecordEntity.STATUS_YES);
		ModelResult<List<InvestorRecordEntity>> modelResult = investorService.queryInvestorRecordList(investorRecord);
		if (modelResult.isSuccess()) {
			List<InvestorRecordEntity> recordList = modelResult.getModel();
			for (InvestorRecordEntity rec : recordList) {
				String investorId = rec.getInvestorId();
				BigDecimal investAmount = rec.getInvestAmount();
				BigDecimal expectAmount = rec.getExpectAmount();
				InvestorWalletEntity investorWallet = investorWalletDao.queryInvestorWallet(investorId);
				if (investorWallet == null) {
					logger.error("标的放款钱包流水报错,钱包获取失败 ，investorId：" + investorId);
					throw new RuntimeException("标的放款钱包流水报错,钱包获取失败");
				}
				BigDecimal investFrozen = investorWallet.getInvestFrozen().subtract(investAmount);
				BigDecimal awaitPrincipal = investorWallet.getAwaitPrincipal().add(investAmount);
				BigDecimal awaitIncome = investorWallet.getAwaitIncome().add(expectAmount);
				investorWallet.setInvestFrozen(investFrozen);
				investorWallet.setAwaitPrincipal(awaitPrincipal);
				investorWallet.setAwaitIncome(awaitIncome);
				int updateCount = investorWalletDao.updateInvestorWallet(investorWallet);
				if (updateCount <= 0) {
					logger.error("标的放款钱包流水报错,钱包更新失败,wallet:" + investorWallet.toString());
					throw new RuntimeException("标的放款钱包流水报错,钱包更新失败");
				}
				InvestorWalletFlowEntity investorWalletFlow = new InvestorWalletFlowEntity();
				try {
					BeanUtils.copyProperties(investorWalletFlow, investorWallet);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				investorWalletFlow.setTransType(TransType.FREEZE_TO_AWAIT);// 标的放款:投资冻结待收金额
				investorWalletFlow.setId(null);
				investorWalletFlow.setTransBalance(investAmount);
				int walletFlowCount = investorWalletDao.insertInvestorWalletFlow(investorWalletFlow);
				if (walletFlowCount <= 0) {
					logger.error("标的放款钱包流水报错,钱包流水添加失败,WalletFlow:" + investorWalletFlow.toString());
					throw new RuntimeException("标的放款钱包流水报错,钱包流水添加失败");
				}
			}
		}
		result.setModel(true);
		return result;
	}

	@Override
	public ModelResult<Boolean> insertInvestorWalletPay(InvestorWalletPayEntity investorWalletPay) {
		ModelResult<Boolean> result = new ModelResult<>();
		try {
			int bool = investorWalletDao.insertInvestorWalletPay(investorWalletPay);
			if (bool > 0) {
				result.withModel(true);
			}
			result.withModel(false);
		} catch (Exception e) {
			logger.error("新增支付记录失败, investorWalletPay:{}", investorWalletPay.toString());
			result.withError("InvestorWalletServiceInnerImpl.insertInvestorWalletPay", "新增支付记录失败");
			e.printStackTrace();
			return result;
		}
		return result;
	}

	@Override
	public ModelResult<Boolean> updateInvestorWalletPay(InvestorWalletPayEntity investorWalletPay) {
		ModelResult<Boolean> result = new ModelResult<>();
		try {
			int bool = investorWalletDao.updateInvestorWalletPay(investorWalletPay);
			if (bool > 0) {
				result.withModel(true);
			}
			result.withModel(false);
		} catch (Exception e) {
			logger.error("修改支付状态失败, investorWalletPay:{}", investorWalletPay.toString());
			result.withError("InvestorWalletServiceInnerImpl.updateInvestorWalletPay", "修改支付状态失败");
			e.printStackTrace();
			return result;
		}
		return result;
	}

	@Override
	@Transactional(transactionManager = "transactionManager")
	public ModelResult<Boolean> investorWalletPay(String requestno) {
		ModelResult<Boolean> result = new ModelResult<>();
		if (requestno == null || requestno.isEmpty()) {
			logger.error("充值失败，参数为空, requestno:{}", requestno);
			return result.withError("InvestorServiceInnerImpl.investorWalletPay", "充值失败，参数为空");
		}
		InvestorWalletPayEntity walletPay = investorWalletDao.queryInvestorWalletPayById(requestno);
		if (walletPay == null) {
			logger.error("充值失败,无法获取钱包充值记录 ，requestno：" + requestno);
			throw new RuntimeException("充值失败");
		}
		if (walletPay.getStatus() == InvestorWalletPayEntity.PAY_SUCCESS) {
			logger.error("充值失败,充值流水重复提交 ，requestno：" + requestno);
			throw new RuntimeException("充值失败");
		}
		// 修改钱包余额
		String investorId = walletPay.getInvestorId();
		InvestorWalletEntity wallet = investorWalletDao.queryInvestorWallet(investorId);
		if (wallet == null) {
			logger.error("充值失败,无法获取钱包 ，walletPay：" + walletPay.toString());
			throw new RuntimeException("充值失败");
		}
		BigDecimal currentBalance = wallet.getCurrentBalance().add(walletPay.getAmount());
		wallet.setCurrentBalance(currentBalance);
		BigDecimal accumulateRecharge = wallet.getAccumulateRecharge().add(walletPay.getAmount());
		wallet.setAccumulateRecharge(accumulateRecharge);
		int updateWalletResult = investorWalletDao.updateInvestorWallet(wallet);
		if (updateWalletResult <= 0) {
			logger.error("充值失败 ，用户钱包修改失败：" + wallet.toString());
			throw new RuntimeException("充值失败");
		}
		// 钱包流失
		InvestorWalletFlowEntity walletFlow = new InvestorWalletFlowEntity();
		try {
			BeanUtils.copyProperties(walletFlow, wallet);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		walletFlow.setTransType(TransType.RECHARGE);// 充值
		walletFlow.setId(null);
		walletFlow.setTransBalance(walletPay.getAmount());
		int updateWalletFlowResult = investorWalletDao.insertInvestorWalletFlow(walletFlow);
		if (updateWalletFlowResult <= 0) {
			logger.error("充值失败 ，用户钱包流水新增失败：" + walletFlow.toString());
			throw new RuntimeException("充值失败");
		}
		// 修改 充值记录状态
		InvestorWalletPayEntity investorWalletPay = new InvestorWalletPayEntity();
		investorWalletPay.setId(requestno);
		investorWalletPay.setStatus(InvestorWalletPayEntity.PAY_SUCCESS);
		investorWalletPay.setWalletId(wallet.getId());
		int count = investorWalletDao.updateInvestorWalletPay(investorWalletPay);
		if (count <= 0) {
			logger.error("充值失败 ，investorWalletPay：" + investorWalletPay.toString());
			throw new RuntimeException("充值失败");
		}
		result.setModel(true);
		return result;
	}

	@Override
	@Transactional(transactionManager = "transactionManager")
	public ModelResult<Boolean> investorWalletWithdraw(InvestorEntity investor, BigDecimal drawMoney) {
		// 校验
		ModelResult<Boolean> result = new ModelResult<>();
		if (investor == null || drawMoney == null) {
			logger.error("提款钱包流水失败，参数为空, investor:{}, investor:{}", investor, drawMoney);
			return result.withError("InvestorServiceInnerImpl.investorWalletWithdraw", "提款钱包流水失败，参数为空");
		}
		// 钱包 --提现冻结
		String investorId = investor.getId();
		InvestorWalletEntity wallet = investorWalletDao.queryInvestorWallet(investorId);
		if (wallet == null) {
			logger.error("提款钱包流水失败,无法获取钱包 ，walletPay：" + wallet.toString());
			throw new RuntimeException("提款钱包流水失败");
		}
		if (wallet.getCurrentBalance().compareTo(drawMoney) <= 0) {
			logger.error("提款钱包流水失败，余额不足, currentBalance:{}, drawMoney:{}", wallet.getCurrentBalance(), drawMoney);
			return result.withError("InvestorServiceInnerImpl.investorWalletWithdraw", "提款钱包流水失败，余额不足");
		}
		BigDecimal currentBalance = wallet.getCurrentBalance().subtract(drawMoney);
		wallet.setCurrentBalance(currentBalance);
		BigDecimal withdrawFrozen = wallet.getWithdrawFrozen().add(drawMoney);
		wallet.setWithdrawFrozen(withdrawFrozen);
		int updateWalletResult = investorWalletDao.updateInvestorWallet(wallet);
		if (updateWalletResult <= 0) {
			logger.error("提款钱包流水失败 ，用户钱包修改失败：" + wallet.toString());
			throw new RuntimeException("提款钱包流水失败");
		}
		// 钱包流水
		InvestorWalletFlowEntity walletFlow = new InvestorWalletFlowEntity();
		try {
			BeanUtils.copyProperties(walletFlow, wallet);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		walletFlow.setTransType(TransType.WITHDRAW_FREEZE);// 提现冻结
		walletFlow.setId(null);
		walletFlow.setTransBalance(drawMoney);
		int updateWalletFlowResult = investorWalletDao.insertInvestorWalletFlow(walletFlow);
		if (updateWalletFlowResult <= 0) {
			logger.error("提款钱包流水失败 ，用户钱包流水新增失败：" + walletFlow.toString());
			throw new RuntimeException("提款钱包流水失败");
		}
		// TODO 提款记录
		InvestorWithdrawRecordEntity withdrawRecord = new InvestorWithdrawRecordEntity();
		withdrawRecord.setInvestorId(investorId);
		withdrawRecord.setApplyAmount(drawMoney);
		withdrawRecord.setStatus(InvestorWithdrawRecordEntity.STATUS_NOT_AUDITED);
		int count = investorWalletDao.insertWithdrawRecord(withdrawRecord);
		if (count <= 0) {
			logger.error("提款钱包流水失败 ，withdrawRecord：" + withdrawRecord.toString());
			throw new RuntimeException("提款钱包流水失败 ");
		}
		result.setModel(true);
		return result;
	}

	@Override
	@Transactional(transactionManager = "transactionManager")
	public ModelResult<Boolean> investorWalletWithdrawConfirm(String requestno) {
		// 校验
		ModelResult<Boolean> result = new ModelResult<>();
		if (StringUtils.isBlank(requestno)) {
			logger.error("提款确认钱包流水失败,参数为空，requestno：" + requestno);
			throw new RuntimeException("提款确认钱包流水失败");
		}
		// 钱包 --提现冻结转提现
		InvestorWithdrawRecordEntity withdrawRecord = investorWalletDao.queryWithdrawRecordByrequestno(requestno);
		if (withdrawRecord == null) {
			logger.error("提款确认钱包流水失败,无法提款记录 ，requestno：" + requestno);
			throw new RuntimeException("提款确认钱包流水失败");
		}
		String investorId = withdrawRecord.getInvestorId();
		InvestorWalletEntity wallet = investorWalletDao.queryInvestorWallet(investorId);
		if (wallet == null) {
			logger.error("提款确认钱包流水失败,无法获取钱包 ，wallet：" + wallet.toString());
			throw new RuntimeException("提款确认钱包流水失败");
		}
		BigDecimal withdrawAmount = withdrawRecord.getApplyAmount();
		BigDecimal withdrawFrozen = wallet.getWithdrawFrozen().subtract(withdrawAmount);
		wallet.setWithdrawFrozen(withdrawFrozen);
		BigDecimal accumulateWithdraw = wallet.getAccumulateWithdraw().add(withdrawAmount);
		wallet.setAccumulateWithdraw(accumulateWithdraw);
		int updateWalletResult = investorWalletDao.updateInvestorWallet(wallet);
		if (updateWalletResult <= 0) {
			logger.error("提款确认钱包流水失败 ，用户钱包修改失败：" + wallet.toString());
			throw new RuntimeException("提款确认钱包流水失败");
		}
		// 钱包流水
		InvestorWalletFlowEntity walletFlow = new InvestorWalletFlowEntity();
		try {
			BeanUtils.copyProperties(walletFlow, wallet);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		walletFlow.setTransType(TransType.FREEZE_TO_WITHDRAW);// 提款冻结转提款
		walletFlow.setId(null);
		walletFlow.setTransBalance(withdrawAmount);
		int updateWalletFlowResult = investorWalletDao.insertInvestorWalletFlow(walletFlow);
		if (updateWalletFlowResult <= 0) {
			logger.error("提款确认钱包流水失败 ，用户钱包流水新增失败：" + walletFlow.toString());
			throw new RuntimeException("提款确认钱包流水失败");
		}
		// 提款记录--提款成功
		withdrawRecord.setStatus(InvestorWithdrawRecordEntity.STATUS_SUCCESS_WITHDRAW);
		int count = investorWalletDao.insertWithdrawRecord(withdrawRecord);
		if (count <= 0) {
			logger.error("提款确认钱包流水失败 ，withdrawRecord：" + withdrawRecord.toString());
			throw new RuntimeException("提款确认钱包流水失败 ");
		}
		result.setModel(true);
		return result;
	}

	@Override
	public ModelResult<Boolean> insertWithdrawRecord(InvestorWithdrawRecordEntity withdrawRecord) {
		ModelResult<Boolean> result = new ModelResult<>();
		try {
			int bool = investorWalletDao.insertWithdrawRecord(withdrawRecord);
			if (bool > 0) {
				result.withModel(true);
			} else {
				result.withModel(false);
			}
		} catch (Exception e) {
			logger.error("新增提款记录失败, withdrawRecord:{}", withdrawRecord.toString());
			result.withError("InvestorWalletServiceInnerImpl.insertWithdrawRecord", "新增提款记录失败");
			e.printStackTrace();
			return result;
		}
		return result;
	}

	@Override
	public ModelResult<Boolean> updateWithdrawRecord(InvestorWithdrawRecordEntity withdrawRecord) {
		ModelResult<Boolean> result = new ModelResult<>();
		try {
			int bool = investorWalletDao.updateWithdrawRecord(withdrawRecord);
			if (bool > 0) {
				result.withModel(true);
			} else {
				result.withModel(false);
			}
		} catch (Exception e) {
			logger.error("修改提款记录失败, withdrawRecord:{}", withdrawRecord.toString());
			result.withError("InvestorWalletServiceInnerImpl.updateWithdrawRecord", "修改提款记录失败");
			e.printStackTrace();
			return result;
		}
		return result;
	}

	@Override
	public ModelResult<InvestorWithdrawRecordEntity> queryWithdrawRecordById(String id) {
		ModelResult<InvestorWithdrawRecordEntity> result = new ModelResult<>();
		try {
			if (StringUtils.isBlank(id)) {
				logger.error("提款记录查询失败,参数为空，id：" + id);
				return result;
			}
			InvestorWithdrawRecordEntity entity = investorWalletDao.queryWithdrawRecordById(id);
			result.withModel(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ModelResult<PageResult<Object[]>> findPageInvestorWithdrawRecord(InvestorWithdrawRecordVO vo) {
		ModelResult<PageResult<Object[]>> result = new ModelResult<PageResult<Object[]>>();
		try {
			result.setModel(investorWalletDao.findPageInvestorWithdrawRecord(vo));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("后台分页查询用户提现记录：", e.getMessage());
		}
		return result;
	}

	@Override
	@Transactional(transactionManager = "transactionManager")
	public ModelResult<Boolean> repaymentWalletHandle(List<RepaymentVO> repayments) {
		logger.info("开始.........还款钱包流水，repayments size:{},repayments:{}", repayments.size(),repayments.toString());
		ModelResult<Boolean> result = new ModelResult<>();
		int count=0;
		for (RepaymentVO repaymentVO : repayments) {
			count++;
			logger.info("处理第{}条还款钱包流水repayment:{}", count,repaymentVO.toString());
			if (repaymentVO == null || StringUtils.isBlank(repaymentVO.getInvestorId())) {
				logger.error("还款钱包流水插入失败,参数为空，repaymentVO：" + repaymentVO.toString());
				throw new RuntimeException("还款钱包流水插入失败");
			}
			BigDecimal income = repaymentVO.getIncome();
			BigDecimal principal = repaymentVO.getPrincipal();
			if (income == null || principal == null || income.compareTo(BigDecimal.ZERO) <= 0
					|| principal.compareTo(BigDecimal.ZERO) <= 0) {
				logger.error("还款钱包流水插入失败,还款本金或还款利息为空，repaymentVO：" + repaymentVO.toString());
				throw new RuntimeException("还款钱包流水插入失败");
			}
			// 钱包流水
			String investorId = repaymentVO.getInvestorId();
			InvestorWalletEntity wallet = investorWalletDao.queryInvestorWallet(investorId);
			if (wallet == null) {
				logger.error("还款钱包流水插入失败,无法获取钱包 ，investorId：" + investorId);
				throw new RuntimeException("还款钱包流水插入失败");
			}
			logger.info("钱包信息，repaymentVO:{},wallet:{}", repaymentVO.toString(),wallet.toString());
			BigDecimal currentBalance = wallet.getCurrentBalance().add(income).add(principal);
			wallet.setCurrentBalance(currentBalance);
			BigDecimal accumulateIncome = wallet.getAccumulateIncome().add(income);
			wallet.setAccumulateIncome(accumulateIncome);
			BigDecimal awaitPrincipal = wallet.getAwaitPrincipal().subtract(principal);
			wallet.setAwaitPrincipal(awaitPrincipal);
			BigDecimal awaitIncome = wallet.getAwaitIncome().subtract(income);
			wallet.setAwaitIncome(awaitIncome);
			if (awaitPrincipal.compareTo(BigDecimal.ZERO) == -1 || awaitIncome.compareTo(BigDecimal.ZERO) == -1) {
				logger.error("还款钱包流水插入失败,还款金额大于待收本金、待收利息，repaymentVO:{},wallet:{}", repaymentVO.toString(),
						wallet.toString());
				throw new RuntimeException("还款钱包流水插入失败");
			}
			int updateWalletResult = investorWalletDao.updateInvestorWallet(wallet);
			if (updateWalletResult <= 0) {
				logger.error("还款钱包流水插入失败，用户钱包修改失败：" + wallet.toString());
				throw new RuntimeException("还款钱包流水插入失败");
			}
			InvestorWalletFlowEntity walletFlow = new InvestorWalletFlowEntity();
			try {
				BeanUtils.copyProperties(walletFlow, wallet);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			walletFlow.setTransType(TransType.REPAYMENT);// 标的还款
			walletFlow.setId(null);
			walletFlow.setTransBalance(income.add(principal));
			int updateWalletFlowResult = investorWalletDao.insertInvestorWalletFlow(walletFlow);
			if (updateWalletFlowResult <= 0) {
				logger.error("还款钱包流水插入失败，用户钱包流水新增失败：" + walletFlow.toString());
				throw new RuntimeException("还款钱包流水插入失败");
			}
		}
		result.setModel(true);
		return result;
	}

}
